﻿using Common.Configurations;
using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;

namespace Common.Extensions;

#nullable disable
/// <summary>
/// 构建应用程序
/// </summary>
public static class ApplicationBuilderExtensions
{
    /// <summary>
    /// 启用服务
    /// </summary>
    /// <param name="app"></param>
    /// <param name="config"></param>
    /// <param name="env"></param>
    /// <returns></returns>
    public static IApplicationBuilder UseDefaultServices(this IApplicationBuilder app, IConfiguration config, IWebHostEnvironment env)
    {
        #region 跨域配置
        app.UseCors(builder =>
        {
            builder.SetIsOriginAllowed(origin => true)
                  .AllowAnyHeader()
           .AllowAnyMethod()
           .AllowCredentials();
        });
        #endregion
        #region HTTPS
        //app.UseHttpsRedirection();
        #endregion
        #region 自定义中间件
        app.UseMiddlewares();
        #endregion
        #region 开启静态文件
        app.UseStaticFiles();
        #endregion
        #region 路由
        app.UseRouting();
        #endregion
        #region 授权认证
        app.UseAuthentication();
        app.UseAuthorization();
        #endregion
        #region 接口文档配置
        var swaggerSettings = config.GetSection(SwaggerSettings.Key).Get<SwaggerSettings>();
        if (swaggerSettings.Enabled)
        {
            app.UseSwagger();
            if (swaggerSettings.UI.ToLower() == "swagger")
            {
                app.UseSwaggerUI();
            }
            else
            {
                app.UseKnife4UI(c =>
                {
                    c.RoutePrefix = ""; // serve the UI at root
                    c.SwaggerEndpoint("/v1/api-docs", "V1 Docs");
                });
            }
        }
        #endregion
        #region 控制器终结点
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers()
            //设置全局使用 Authorize 特性
            .RequireAuthorization(); 
            if (swaggerSettings.UI.ToLower() != "swagger")
            {
                // 添加Knife4j的路由映射
                endpoints.MapGet("/swagger/index.html", context =>
                {
                    context.Response.Redirect("/index.html#/home"); // 将根路径重定向到Knife4j的页面
                    return Task.CompletedTask;
                });
            }
            endpoints.MapSwagger("{documentName}/api-docs");
        });
        #endregion

        return app;
    }
}
